Race timing: Exercise 2.3

Each day, you run 10 km, and want to know how long, on average, that run takes. Write a program that asks the user how long it took to run 10 km today. The programs continues to ask how long (in minutes) it took, until the user presses Enter. At that point, the program exits—but only after calculating and displaying the average time that the 10 km run took.

For example, here is what the program would look like if the user enters three data points:

Enter 10 km run time: 15
Enter 10 km run time: 20
Enter 10 km run time: 10
Enter 10 km run time:
Average of 15.0, over 3 races

Note that the numeric inputs and outputs should all be floating-point values. We know that floats aren’t accurate enough for serious measures, but I don’t think that anyone’s exercise regime will hit a fatal snag just because they got a wrongly nonterminating decimal.


In [9]:
def mean(seq):
    return float(sum(seq)) / len(seq)
    
def calc_mean_pace():
    prompt = "Enter 10 km run time: "
    
    data = []
    
    count = 0
    while count < 5:
        count += 1
        try:
        
            value = raw_input(prompt)
        
            if not value:
                print "Thank you!"
                break
            
            data.append(float(value))
        except Exception as ex:
            print "Apparently it was not a number"
    
    if data:
        msg = "Average of {0}, over {1} races".format(mean(data), len(data))
    else:
        msg = "Cannot calculate, data is empty"
        
    print msg

calc_mean_pace()


Enter 10 km run time: 
Thank you!
Cannot calculate, data is empty

In [ ]: